<template>
    <div class="order">
        <!-- 1、面包屑导航 -->
        <div class="title" style="margin-top:20px;margin-left:20px;margin-bottom: 20px;">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>订单管理</el-breadcrumb-item>
                <el-breadcrumb-item>订单列表</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="order_form">
            <div class="header">
                <el-input type="text" v-model="keyword" placeholder="请通过输入订单号/商品名称/用户名称查询订单" @change="toSearch"></el-input>
                <el-button type="primary" @click="toSearch">搜索</el-button>
            </div>
            <div class="goods_table">
                <el-table ref="orderTable" :data="orderData" tooltip-effect="dark" style="width: 100%"
                    @selection-change="handleSelectionChange" @select="selectionRow" v-loading="loading" border>
                    <el-table-column prop="order_number" label="订单号" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="goods_name" label="商品名称" width="120">
                    </el-table-column>
                    <el-table-column prop="user_name" label="用户名称" width="120">
                    </el-table-column>
                    <el-table-column prop="order_money" label="订单金额" width="120">
                    </el-table-column>
                    <el-table-column prop="order_time" label="下单时间" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="order_address" label="收货地址" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="order_status" label="订单状态" width="120">
                        <template slot-scope="scope">
                            <el-tag type="" v-if="scope.row.order_status=='待发货'">待发货</el-tag>
                            <el-tag type="warning" v-else-if="scope.row.order_status=='待收货'">待收货</el-tag>
                            <el-tag type="success" v-else-if="scope.row.order_status=='已完成'">已完成</el-tag>
                            <el-tag type="danger" v-else>已取消</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" label="操作" show-overflow-tooltip>
                        <template slot-scope="scope">
                            <el-button size="mini" icon="el-icon-edit" type="primary"
                                @click="orderEditor(scope.$index, scope.row)"></el-button>
                            <!-- 地点按钮 -->
                            <el-button type="warning" icon="el-icon-location" size="mini"
                                @click="showProgressBox(scope.$index, scope.row)">
                            </el-button>
                            <el-dialog width="40%" title="物流信息" :visible.sync="ProgressVisible" append-to-body>
                                <el-button size="mini" type="primary" style="margin-bottom:20px;"
                                    @click="ProgressEditor(scope.$index, scope.row)">更新物流</el-button>
                                <el-dialog width="30%" title="更新物流" :visible.sync="updateProgressVisible" @close="updateProgressClose"
                                    append-to-body>
                                    <el-form ref="form" :model="form" label-width="40px">
                                        <el-form-item label="状态">
                                            <el-select v-model="orderForm.status" placeholder="请选择">
                                                <el-option v-for="item in options" :key="item.value" :label="item.label"
                                                    :value="item.value">
                                                </el-option>
                                            </el-select>
                                        </el-form-item>
                                        <el-form-item label="详情">
                                            <el-input v-model="orderForm.detail"></el-input>
                                        </el-form-item>
                                    </el-form>
                                    <div slot="footer" class="dialog-footer">
                                        <el-button @click="updateProgressCancel">取 消</el-button>
                                        <el-button type="primary" @click="updateProgressConfirm">确 定</el-button>
                                    </div>
                                </el-dialog>
                                <div v-if="IsNull">
                                    <div class="radio" style="margin-bottom: 20px;">
                                        排序：
                                        <el-radio-group v-model="reverse">
                                            <el-radio :label="true">倒序</el-radio>
                                            <el-radio :label="false">正序</el-radio>
                                        </el-radio-group>
                                    </div>
                                    <el-timeline :reverse="reverse">
                                        <el-timeline-item v-for="(activity, index) in activities" :key="index"
                                            :timestamp="activity.timestamp">
                                            <h4>{{activity.title}}</h4>
                                            <div style="margin-top:10px;">{{activity.content}}</div>
                                        </el-timeline-item>
                                    </el-timeline>
                                </div>
                                <div v-else style="text-align:center;"><span>暂无物流信息！</span></div>
                                <div slot="footer" class="dialog-footer">
                                    <el-button @click="ProgressCancel">取 消</el-button>
                                    <el-button type="primary" @click="ProgressConfirm">确 定</el-button>
                                </div>
                            </el-dialog>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <MyPage :total="total" :pageSize="pageSize" :currentPage="currentPage" @changePageNum="getPageNum" />
        </div>
    </div>

</template>

<script>

import MyPage from '@/components/Mypage.vue'



export default {
    data() {
        return {
            // [{"title":"已揽收","content":"活动按期开始","timestamp":"2018-04-15"},{"title":"已装车","content":"通过审核","timestamp":"2018-04-13"},{"title":"待出库","content":"创建成功","timestamp":"2018-04-11"}]
            loading:true,
            options: [{
                value: '已揽收',
                label: '已揽收'
            }, {
                value: '已装车',
                label: '已装车'
            }, {
                value: '待出库',
                label: '待出库'
            }, {
                value: '派送中',
                label: '派送中'
            }, {
                value: '已签收',
                label: '已签收'
            }],
            detail: '',
            orderForm: {
                status: '',
                id: '',
                detail: '',

            },
            IsNull: true,
            reverse: true,
            activities: [],
            keyword: '',
            orderData: [],
            multipleSelection: [],
            getOrderList: [],
            searchList: [],
            isSelect: false,
            ProgressVisible: false,
            updateProgressVisible: false,
            total: 10,
            pageSize: 10,
            currentPage: 1,
            type: 2  //2:查询所有商品分页  1:查询搜索列表的分页
        };

    },
    components: {
        MyPage,
    },
    created() {
        let that = this;
        let temp = localStorage.getItem('order_currentPage')
        let temp_type = localStorage.getItem('order_type')
        if (temp_type == 1) {
            this.keyword = localStorage.getItem('order_keyword');
            this.toSearch()
        } else {
            if (temp) {
                this.currentPage = temp;
            }
            that.$nextTick(function () {
                this.getOrder()
            }, 200)
        }
    },
    filters: {
        formatDate: function (value, args) {
            var dt = new Date(value);
            if (args == 'yyyy-M-d') {// yyyy-M-d
                let year = dt.getFullYear();
                let month = dt.getMonth() + 1;
                let date = dt.getDate();
                return `${year}-${month}-${date}`;
            } else if (args == 'yyyy-M-d H:m:s') {// yyyy-M-d H:m:s
                let year = dt.getFullYear();
                let month = dt.getMonth() + 1;
                let date = dt.getDate();
                let hour = dt.getHours();
                let minute = dt.getMinutes();
                let second = dt.getSeconds();
                return `${year}-${month}-${date} ${hour}:${minute}:${second}`;
            } else if (args == 'yyyy-MM-dd') {// yyyy-MM-dd
                let year = dt.getFullYear();
                let month = (dt.getMonth() + 1).toString().padStart(2, '0');
                let date = dt.getDate().toString().padStart(2, '0');
                return `${year}-${month}-${date}`;
            } else {// yyyy-MM-dd HH:mm:ss
                let year = dt.getFullYear();
                let month = (dt.getMonth() + 1).toString().padStart(2, '0');
                let date = dt.getDate().toString().padStart(2, '0');
                let hour = dt.getHours().toString().padStart(2, '0');
                let minute = dt.getMinutes().toString().padStart(2, '0');
                let second = dt.getSeconds().toString().padStart(2, '0');
                return `${year}-${month}-${date} ${hour}:${minute}:${second}`;
            }
        }
    },

    methods: {
        getOrder() {
            this.$ajax({
                method: 'get',
                url: '/api/getOrder',
            }).then(res => {
                
                let data = res.data.data;
                this.getOrderList = data;
                this.orderData = this.getOrderList.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
                console.log('orderData:', this.orderData)
                this.total = data.length;
                if (this.total > 0 && this.orderData.length == 0) {
                    this.currentPage--;
                    localStorage.setItem('order_currentPage', this.currentPage);
                    this.orderData = this.getOrderList.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
                }
                this.loading = false;
            }).catch(function (err) {
                console.log(err)
            })
        },
        toSearch() {
            if (this.keyword) {
                console.log("type=1")
                this.type = 1;
            } else {
                console.log("type=2")
                this.type = 2;
                this.getOrder()
            }
            localStorage.setItem('order_type', this.type);
            localStorage.setItem('order_keyword', this.keyword)

            this.$ajax({
                method: 'get',
                url: '/api/order_search',
                params: { search_word: this.keyword }
            }).then(res => {

                let data = res.data.result
                this.searchList = data;
                this.currentPage = 1;
                this.orderData = this.searchList.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
                this.total = data.length;
                if (this.total > 0 && this.orderData.length == 0) {
                    this.currentPage--;
                    localStorage.setItem('order_currentPage', this.currentPage);
                    this.orderData = this.searchList.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
                }
            }).catch(function (err) {
                console.log(err)
            })

        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        
        handleCheck(index, row) {
            console.log(index, row);
        },
        orderEditor(index,row){
            console.log(row)
            this.$store.commit('setOrderDetail',row)
            this.$router.push('/order_detail')  
        },
        ProgressEditor(index, row) {
            this.updateProgressVisible = true;
        },
        showProgressBox(index, row) {
            this.ProgressVisible = true;
            this.orderForm.id = this.orderData[index].id;
            let data = this.orderData[index].order_message;
            console.log(this.form)
            if (!data) {
                this.IsNull = false;
            } else {
                this.IsNull = true;
            }
            this.activities = JSON.parse(data)
        },
        getPageNum(page) {
            this.currentPage = page
            localStorage.setItem('order_currentPage', this.currentPage)
            console.log("用户列表：", this.getOrdersList)
            if (this.type == 1) {
                this.orderData = this.searchList.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
            } else {
                this.orderData = this.getOrderList.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
            }

        },
        ProgressCancel() {
            this.ProgressVisible = false;
        },
        ProgressConfirm() {
            this.ProgressVisible = false;
        },
        updateProgressCancel() {
            this.updateProgressVisible = false;
            this.clearContent();
        },
        updateProgressClose(){
            this.updateProgressVisible = false;
            this.clearContent();
        },
        updateProgressConfirm() {
            let result = JSON.stringify(this.activities).slice(1, -1)
            let res = ''
            let temp = this.$options.filters['formatDate'];
            let str = '[{"title":"' + this.orderForm.status + '","content":"' + this.orderForm.detail + '","timestamp":"' + temp(new Date()) + '"}'
            if (!this.activities||this.activities.length==0) {
                res = str+']'
            } else {
                res = str + ',' + result+']'
            }
            console.log('res:',res)
            this.orderForm.detail=res;
            this.updateProgressVisible = false;
            this.$ajax({
                method: "post",
                url: "/api/order_updateProgress",
                params: this.orderForm
            }).then(res => {
                console.log(res)
                this.$message({
                    message: '物流更新成功！',
                    type: 'success'
                });
            });   
            this.clearContent();
            this.reload();
        },
        clearContent() {
            this.orderForm.status = '';
            this.orderForm.detail = '';
        }
    },
    inject: ['reload']
}
</script>

<style lang="less" scoped>
.order_form {
    margin: 20px;
    padding: 20px;
    background-color: white;

    .header {
        display: flex;
        margin-bottom: 20px;

        button {
            margin-left: 20px;
        }
    }


    // .goods_page {
    //     margin: 20px auto;
    //     align-content: center;
    //     position: absolute;
    //     left:50%;
    //     top:100%;
    //     transform: translate(-50%,-50%);
    // }
}
</style>